import 'package:intl/intl.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/controllers/space/space_const.dart';
import 'package:share_fit/app/controllers/space/weekly/weekly_item.dart';
import 'package:share_fit/app/controllers/space/weekly/weekly_state.dart';
import 'package:share_fit/app/helper/db/ute_db_helper.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/heart_rate_model.dart';
import 'package:share_fit/app/models/home/sleep_model.dart';
import 'package:share_fit/app/models/home/step_model.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/generated/locales.g.dart';

class WeeklyLogic extends BaseController {

  final WeeklyState state = WeeklyState();

  Future<void> syncWorkoutHistoryData(Map<String, Object> params, {required Null Function(dynamic _) back}) async {
    // var result = await lRemoteReq(WeeklyState.M_syncWorkoutHistoryData, params);
    // back(result);
  }

  void updateWeekly(bool value) {
    state.switchWeekly = value;
    initState();
    update(['switch_weekly']);
  }

  getStepData(String address, String startTime, String endTime) async {
    print('$startTime/$endTime');
    final db = await UteDbHelper.getDB();
    StepModel? steps = await db.stepDao.findForReport(address, startTime, endTime);
    int? step = steps!.step??0;
    double? calories = steps.calories??0;
    int? distance = steps.distance??0;
    print('==================/step:$steps:${steps.step}/calories:${steps.calories}/distance:${steps.distance}=');
    int targetStep = read('sport_target_step', defaultValue: SpaceConst.targetSteps[0], global: true);
    WeeklyItem stepWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_step.ts, step==0?'--':step.toString(), 'step',
      targetStep.toString(), step==0?'--':step<targetStep?LocaleKeys.weekly_low.ts:LocaleKeys.weekly_normal.ts]);
    if(state.weeklyData.isNotEmpty) {
      state.weeklyData[0] = stepWeeklyItem;
    } else {
      state.weeklyData.insert(0, stepWeeklyItem);
    }

    int targetCalories = read('sport_target_calorie', defaultValue: SpaceConst.targetCalories[0], global: true);
    WeeklyItem calorieWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_calorie.ts, calories==0?'--':calories.toString(), 'kcal',
      targetCalories.toString(), calories==0?'--':calories<targetCalories?LocaleKeys.weekly_low.ts:LocaleKeys.weekly_normal.ts]);
    if(state.weeklyData.length>1) {
      state.weeklyData[1] = calorieWeeklyItem;
    } else {
      state.weeklyData.insert(1, calorieWeeklyItem);
    }

    int targetDistance = read('sport_target_distance', defaultValue: SpaceConst.targetDistances[0], global: true);
    WeeklyItem distanceWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_distance.ts, distance==0?'--':(distance/1000).toStringAsFixed(2), 'km',
      targetDistance.toString(), distance==0?'--':distance<targetDistance?LocaleKeys.weekly_low.ts:LocaleKeys.weekly_normal.ts]);
    if(state.weeklyData.length>2) {
      state.weeklyData[2] = distanceWeeklyItem;
    } else {
      state.weeklyData.insert(2, distanceWeeklyItem);
    }
    update(['weekly_tabview']);
    // db.close();
  }

  getSleepData(String address, String startTime, String endTime) async {
    final db = await UteDbHelper.getDB();
    List<SleepModel> sleeps = await db.sleepDao.findForReport(address, startTime, endTime);
    print('sleeps length:${sleeps.length}');
    double sleep = 0;
    sleeps.forEach((element) {
      sleep += element.sleepTime!;
      print('sleepTime:${element.sleepTime}');
    });

    sleep = sleep/60;
    print('sleep/day:$sleep');
    WeeklyItem sleepWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_sleep.ts, sleep==0||sleep.isNaN?'--':sleep.toStringAsFixed(2), 'hour',
      '8', sleep==0||sleep.isNaN?'--':sleep<8?LocaleKeys.weekly_low.ts:LocaleKeys.weekly_normal.ts]);
    if(state.weeklyData.length>3) {
      state.weeklyData[3]=sleepWeeklyItem;
    } else {
      state.weeklyData.insert(3, sleepWeeklyItem);
    }

    update(['weekly_tabview']);
  }

  getRateData(String address, String startTime, String endTime) async {
    final db = await UteDbHelper.getDB();
    List<HeartRateModel> rates = await db.heartRateDao.findForReport(address, startTime, endTime);
    double rate = 0;
    int length = rates.length;
    print('rate length:${rates.length}');
    rates.forEach((element) {
      rate += element.heartRateAvg??0;
      // print('rate:${element.heartRateAvg}/');
    });
    rate = rate/length;
    WeeklyItem rateWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_rate.ts, rate==0||rate.isNaN?'--':rate.round().toString(), 'bpm',
      '60-100', rate==0||rate.isNaN?'--':60>rate?LocaleKeys.weekly_low.ts:rate>100?LocaleKeys.weekly_high.ts:LocaleKeys.weekly_normal.ts]);
    if(state.weeklyData.length>4) {
      state.weeklyData[4] = rateWeeklyItem;
    } else {
      state.weeklyData.insert(4, rateWeeklyItem);
    }
    update(['weekly_tabview']);
  }

  getPressureData(String startTime, String endTime) async {
    WeeklyItem pressureWeeklyItem = WeeklyItem(data: [LocaleKeys.weekly_pressure.ts, '--', 'mmHg', '70-115', '--']);
    // if(state.weeklyData.length>5) {
    //   state.weeklyData[5]=pressureWeeklyItem;
    // } else {
    //   state.weeklyData.insert(5, pressureWeeklyItem);
    // }
    // update(['weekly_tabview']);
  }

  String getDate() {
    DateTime now = DateTime.now();
    DateTime startTime = now.subtract(Duration(days: now.weekday-1));

    if(state.switchWeekly) {
      now = startTime.subtract(Duration(days: 1));
      startTime = now.subtract(Duration(days: now.weekday-1));
    }
    String startMonth = startTime.month.toString().padLeft(2, '0');
    String startDay = startTime.day.toString().padLeft(2, '0');

    String endMonth = now.month.toString().padLeft(2, '0');
    String endDay = now.day.toString().padLeft(2, '0');

    return '${startTime.year}/$startMonth/$startDay-${now.year}/$endMonth/$endDay';
  }

  @override
  String getRemotePath() {
    return WeeklyState.REMOTE_PATH;
  }

  @override
  void initState() async {
    if(state.weeklyData.length>6) {
      state.weeklyData.removeRange(6, state.weeklyData.length);
    }
    DateTime now = DateTime.now();
    DateTime startTime = now.subtract(Duration(days: now.weekday-1));

    if(state.switchWeekly) {
      now = startTime.subtract(Duration(days: 1));
      startTime = now.subtract(Duration(days: now.weekday-1));
    }

    String address = read(UTEPedConst.keyAddress, global: true);
    await getStepData(address, DateFormat('yyyyMMdd').format(startTime), DateFormat('yyyyMMdd').format(now));
    await getSleepData(address, DateFormat('yyyyMMdd').format(startTime), DateFormat('yyyyMMdd').format(now));
    await getRateData(address, DateFormat('yyyyMMdd').format(startTime), DateFormat('yyyyMMdd').format(now));
    await getPressureData(DateFormat('yyyyMMdd').format(startTime), DateFormat('yyyyMMdd').format(now));
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
    print('omRemoteEvent'+event);
  }
}